define(function (require, exports, module) {

    require("apps/best/page.css");
    require("apps/grid");
    require("apps/easyui");
    var comp = require("apps/lab/components");
    var filedComponent = comp.components;

    exports.init = function (ctx, uuid) {
        var page = new $.PageDomFactory(uuid);

        var pageListComponent = new $.PageListComponent(uuid, {
            view: {
                grid: "grid",
                myToolbar: "nsdb",
                colbar: "colbar"
            },
            configs: {
                gridUrl: ctx + "/app/api/best/processList",
                idField: "id",
                gridColumns: [
                    {
                        field: 'id',
                        checkbox: true
                    },
                    {
                        field: 'temp1',
                        hidden: true
                    },
                    {
                        field: 'title',
                        title: '名称',
                        width: 100,
                        align: 'left'
                    },
                    {
                        field: 'reason',
                        title: '推荐原因',
                        width: 300,
                        align: 'left'
                    },
                    {
                        field: 'remark',
                        title: '备注',
                        width: 100,
                        hidden: true,
                        align: 'left'
                    },
                    {
                        field: 'createTime',
                        title: '创建时间',
                        width: 100,
                        align: 'left'
                    }
                ]
            },
            events: {
                renderColBarBefore: function (key, row) {
                    return true;
                },
                onClickColBtn: function (context, btn, row) {
                    switch (btn.key) {
                        case "view":
                            whenView(context, row);
                            break;
                        case "viewParams":
                            whenViewParams(context, row);
                            break;
                        case "update":
                            whenUpdate(context, btn.href, row);
                            break;
                        default :
                            break;
                    }
                },
                onClickToolbarBtn: function (context, btn) {
                    switch (btn.key) {
                        case "search_all":
                            context.searchAll();
                            break;
                        case "search":
                            context.search(btn.href, "最优流程搜索", "best_process_search");
                            break;
                        case "del":
                            context.del(btn.href);
                            break;
                        case "add":
                            whenAdd(context, btn.href);
                            break;
                        default :
                            break;
                    }
                }
            }
        });

        function whenView(context, row) {
            context.detail("最优流程详情查看", row);
        }

        function whenAdd(context, href) {
            globalWindow.create({
                href: href,
                title: "新增流程",
                method: "addBestProcess",
                width: 1000,
                callback: function (status) {
                    if (status) {
                        context.grid.datagrid("reload")
                    }
                }
            });
            globalWindow.open();
        }

        function whenUpdate(context, href, row) {
            globalWindow.create({
                href: href,
                title: "修改流程",
                method: "updateBestProcess",
                width: 1000,
                callback: function (status) {
                    if (status) {
                        context.grid.datagrid("reload")
                    }
                }
            });
            globalWindow.open();
        }

        var globalWindow = new $.PageWindow();

        function whenViewParams(context, row) {
            globalWindow.create({
                width: 800,
                href: ctx + "/app/api/best/bestProcess?id=" + row.id,
                title: "工艺流程详情"
            });
            globalWindow.open();
        }
    };

    var tempateForParam = '{{#.}}<div class="param-item" data-record-id="{{id}}" data-name="{{tProcessTemplate.processName}}" data-cover="{{tProcessTemplate.processCover}}" data-ref="{{record.id}}">' +
        '<h3 class="title">' +
        '{{tProcessTemplate.processName}}<span><i class="checked-flag fa fa-check fa-lg"></i></span></h3>' +
        '<table class="param-des">' +
        '<tr><th class="title">推荐人：</th>' +
        '<td>{{operator}}</td></tr>' +
        '<tr><th class="title">推荐原因：</th>' +
        '<td>{{reason}}</td></tr></table>' +
        '<h3 class="param-title mt10">详细参数：</h3>' +
        '<table class="params">' +
        '<tr><th class="title">参数名称</th><th class="title">参数值</th>' +
        '<th class="title">单位</th><th class="title">测量设备</th></tr>' +
        '{{#tProcessParameters}}<tr data-id="param-info" data-field-name="{{fieldName}}" data-field-type="{{fieldType}}" data-parameter-value="{{parameterValue}}" data-unit="{{unit}}" data-parameter-device="{{parameterDevice}}"><td>{{fieldName}}</td>' +
        '<td>{{{parameterValue}}}</td><td>{{unit}}</td><td>{{parameterDevice}}</td>' +
        '</tr>{{/tProcessParameters}}</table></div>{{/.}}';

    var processSelectedTemplate = '<div data-id="{{id}}" data-ref="{{recordId}}" class="selected-process">' +
        '<span class="row-number">{{rowNumber}}</span><dl data-item="{{id}}" class="process-detail" data-name="{{processName}}"><dt>' +
        '<img src="{{_processCover}}" style="width: 128px;height: 128px"/></dt><dd>{{processName}}</dd></dl>' +
        '<div class="action">' +
        '<a href="javascript:void(0)" data-id="param-btn" data-type="moveLeft" title="左移" iconCls="fa fa-long-arrow-left fa-lg" plain="true"></a>' +
        '<a href="javascript:void(0)" data-id="param-btn" data-type="removeProcess" iconCls="fa fa-trash fa-lg" title="移除" plain="true"></a>' +
        '<a href="javascript:void(0)" data-id="param-btn" data-type="moveRight" title="右移" iconCls="fa fa-long-arrow-right fa-lg" plain="true"></a></div><div>';
    var templateForDialog = '<div class="input-250"><div class="box_tc_s">' +
        '<table border="1" cellpadding="0" cellspacing="0" class="hydra-table">' +
        '{{#.}}<tr class="hydra-tr-bg"><td class="hydra-left">{{fieldName}}</td>' +
        '<td class="hydra-right"><input type="hidden" value="{{fieldName}}" name="fieldName" />' +
        '<input type="hidden" value="{{unit}}" name="unit" /><input type="hidden" value="{{fieldType}}" name="fieldType" />' +
        '<input type="hidden" value="{{orderNo}}" name="orderNo" />' +
        '<input type="hidden" value="{{parameterDevice}}" name="parameterDevice" />' +
        '<span data-id="component">组件加载中</span>{{unit}}</td></tr>{{/.}}</table></div></div>';
    var imgsTypes = ["jpg","jpeg", "gif", "png", "bmp"];
    var renderMethods = {
        FIELD_TYPE_ATTACHMENT: function (ctx, v) {
            if (v && v.length && v.lastIndexOf(".") > 0) {
                var vv = v.substr(v.lastIndexOf(".") + 1);
                var p = ctx + '/download/' + v;
                if (imgsTypes.contains(vv.toLocaleLowerCase())) {
                    p = ctx + '/print/' + v;
                    return "<a href=\"" + p + "\" data-id=\"facybox\"><img style=\"width:60px;height:30px;\" src=\"" + p + "\"></a>";
                }
            }
            return v && v.length ? '<a href="' + ctx + '/download/' + v + '">附件下载</a>' : "";
        },
        FIELD_TYPE_SCIENTIFIC: function (ctx, v) {
            if (v && v.length) {
                var vv = v.split(",");
                if (vv.length == 2) {
                    return vv[0] + "×10&sup" + vv[1] + ";";
                } else {
                    return vv[0] + "×10&sup" + 0 + ";";
                }
            }
            return "";
        }
    };
    var paramBtnEvents = {
        moveLeft: function (page, _da) {
            var dom = $(_da).closest(".selected-process");
            var prev = dom.prev();
            if (prev.length) {
                dom.fadeOut(function () {
                    $(this).insertBefore(prev).fadeIn(function () {
                        toggleHideBtn(page);
                    });
                });
            }
        },
        moveRight: function (page, _da) {
            var dom = $(_da).closest(".selected-process");
            var next = dom.next();
            if (next.length) {
                dom.fadeOut(function () {
                    $(this).insertAfter(next).fadeIn(function () {
                        toggleHideBtn(page);
                    });
                });
            }
        },
        removeProcess: function (page, dom) {
            $(dom).closest(".selected-process").fadeOut(function(){
                $(this).remove();
                toggleHideBtn(page);
            });
        }
    };

    function ComparePanel(ctx, id, callback){
        var template = '<div><div data-id="param-process" class="param-process-box"></div></div>';
        var uuid = $.utils.createUUID(6);
        var that = this;
        this.wedget = $(template).appendTo("body").attr("id", uuid)
        var page = new $.PageDomFactory(uuid);
        this.wedget.dialog({
            title: "选择最优参数",
            width: 800,
            closed:true,
            loadingMessage: '页面加载中，请稍后...',
            modal: true,
            onClose: function(){
                that.wedget.dialog("destroy");
                that.wedget.remove();
            },
            buttons: [
                {
                    text: "确定",
                    handler: function () {
                        buildSelected(ctx, page, page.getJqDom("param-process").children().filter(".clicked"));
                        that.wedget.dialog("close");
                        callback();
                    }
                },
                {
                    text: "关闭",
                    handler: function () {
                        that.wedget.dialog("close");
                    }
                }
            ]
        });
        buildData(ctx, id, {success: function (results) {
            var pro = page.getJqDom("param-process");
            pro.html(Mustache.render(tempateForParam, results))
                .find("[data-id=param-info]").each(function () {
                    var fieldType = $(this).attr("data-field-type");
                    comp.render(ctx, fieldType, $(this).find("td").eq(1));
                }).end().children().each(function(i, item){
                    if(i == 0){
                        $(this).addClass("clicked");
                    }
                    $(this).on("click", function(){
                        if($(this).hasClass("clicked")){
                            return;
                        }
                        pro.children().removeClass("clicked");
                        $(this).addClass("clicked");
                    })
                });
            that.wedget.dialog("open");
            that.wedget.dialog("center");
        }});
        var detailCache = {};

        function buildData(ctx, id, listener) {
            var results = [];
            $.getJSON(ctx + "/app/api/best/processBestRecords", {id: id}, function (data) {
                if ($.isPlainObject(data) && data.error) {
                    $.messager.alert('信息',
                        data.msg, 'error');
                } else {
                    var _data = FastJson.format(data);
                    if(_data.length){
                        _data[0].checked = "checked";
                    }
                    listener.success(_data);
                }
            })
        }
    }
    function buildSelected(ctx, page, dom) {
        var joinDom = dom;
        var params = [];
        dom.find("[data-id=param-info]").each(function () {
            var _data = $(this).data();
            params.push(_data);
        });
        var row = {
            id: dom.attr("data-record-id"),
            recordId: dom.attr("data-record-id"),
            processName: dom.attr("data-name"),
            processCover: dom.attr("data-cover"),
            rowNumber: page.getJqDom("process").children().length + 1,
            _processCover:ctx + "/print/" + dom.attr("data-cover")
        };
        page.getJqDom("process").append(Mustache.render(processSelectedTemplate, row)).find("[data-id=param-btn]").linkbutton({
            onClick: function () {
                var type = $(this).attr("data-type");
                paramBtnEvents[type](page, this);
            }
        });
        toggleHideBtn(page);
    }
    function toggleHideBtn(page) {
        page.getJqDom("param-btn").show();
        var children = page.getJqDom("process").children().each(function(i, item){
            if(i == 0){
                $(this).find("[data-type=moveLeft]").hide();
            }
            $(this).find(".row-number").html(i+1);
        });
        children.eq(-1).find("[data-type=moveRight]").hide();
    }

    function initSavePanel(ctx, page){
        page.getJqDom("accordion").accordion().find(".panel-tool").hide();
        page.getJqDom("lab-item").on("click", function () {
            if($(this).find(".best-total").html() == "0"){
                return;
            }
            var id = $(this).attr("data-process-id");
            new ComparePanel(ctx, id, function(){
                page.getJqDom("accordion").accordion("select", "流程提交");
            });
        });
        page.getJqDom("goToChooseProcess").linkbutton({
            onClick:function(){
                page.getJqDom("accordion").accordion("select", "选择工艺模板");
            }
        });
        page.getJqDom("lab-title").each(function () {
            var h = $(this).html();
            h = h.length > 4 ? h.substr(0, 3) + "..." : h;
            $(this).html(h);
        });
    }

    exports.add = function (ctx, uuid) {
        var page = new $.PageDomFactory(uuid, true);
        initSavePanel(ctx, page);
        window.addBestProcess = function (win) {
            var baseForm = page.getJqDom("baseForm");
            if (!baseForm.form("validate")) {
                return false;
            }
            var records = [];
            page.getJqDom("process").children().each(function(){
                records.push({id:$(this).attr("data-ref")});
            });
            if (records.length < 2) {
                $.messager.alert("信息", "保存的最优流程至少需要两个及以上的流程过程", 'error');
                return false;
            }
            $.messager.confirm("消息", "是否保存该流程为最优工作流程", function (arg) {
                if (arg) {
                    var postData = baseForm.serializeJson();
                    postData.records = records;
                    win.wait("start", "最优流程保存中，请稍后");
                    $.post(ctx + "/app/api/best/addProcess", $.utils.buildJson(postData), function (json) {
                        if ($.isPlainObject(json) && json.error) {
                            $.messager.alert('信息',
                                json.msg, 'error');
                            win.wait("end");
                        } else {
                            $.messager.alert('信息',
                                '保存成功', 'info');
                            win.callback(true);
                            win.wait("end");
                            win.close();
                        }
                    }, "JSON");
                }
            });
        }
    };

    exports.update = function (ctx, uuid, config) {
        var page = new $.PageDomFactory(uuid, true);
        initSavePanel(ctx, page);

        page.getJqDom("process").find("[data-id=param-btn]").linkbutton({
            onClick: function () {
                var type = $(this).attr("data-type");
                paramBtnEvents[type](page, this);
            }
        });
        toggleHideBtn(page);

        window.updateBestProcess = function (win) {
            var baseForm = page.getJqDom("baseForm");
            if (!baseForm.form("validate")) {
                return false;
            }
            var records = [];
            page.getJqDom("process").children().each(function () {
                records.push({
                    id: $(this).attr("data-ref")
                })
            });
            if (records.length < 2) {
                $.messager.alert("信息", "保存的最优流程至少需要两个及以上的流程过程", 'error');
                return false;
            }
            $.messager.confirm("消息", "是否确认修改该流程", function (arg) {
                if (arg) {
                    var postData = baseForm.serializeJson();
                    postData.records = records;
                    win.wait("start", "最优流程保存中，请稍后");
                    $.post(ctx + "/app/api/best/updateProcess", $.utils.buildJson(postData), function (json) {
                        if ($.isPlainObject(json) && json.error) {
                            $.messager.alert('信息',
                                json.msg, 'error');
                            $("body").wait("end");
                        } else {
                            $.messager.alert('信息',
                                '保存成功', 'info');
                            win.callback(true);
                            win.close();
                        }
                    }, "JSON");
                }
            });
        }
    };

    exports.search = function (ctx, uuid) {
        var page = new $.PageDomFactory(uuid, true);
        window.best_process_search = function (win) {
            win.wait("start", "搜索中,请稍候.");
            var form = page.getJqDom("search-form");
            var postData = form.serializeJson();
            win.callback(postData);
            win.close();
        }
    }
});